<template>
  <div class="agriculture-product-container">
    <!-- 发布助农商品按钮 -->
    <el-button type="primary" @click="showAddDialog">发布助农商品</el-button>

    <!-- 查询条件 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable @clear="handleSearch" />
        </el-form-item>
        <el-form-item label="商品产地">
          <el-input v-model="searchForm.origin" placeholder="请输入商品产地" clearable @clear="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable @clear="handleSearch">
            <el-option label="上架中" :value="1" />
            <el-option label="已下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 助农商品表格 -->
    <el-table :data="paginatedData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="商品ID" width="100" />
      <el-table-column prop="name" label="商品名称" width="180" />
      <el-table-column prop="description" label="商品描述" width="200" show-overflow-tooltip />
      <el-table-column prop="price" label="价格(元)" width="120">
        <template #default="{ row }">
          {{ row.price?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="unit" label="单位" width="100" />
      <el-table-column prop="origin" label="产地" width="150" />
      <el-table-column prop="isAgriculture" label="是否助农" width="120">
        <template #default="{ row }">
          {{ row.isAgriculture === '1' ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column prop="sales" label="销量" width="100" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'warning'">
            {{ row.status === 1 ? '上架中' : '为上架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加助农商品弹窗 -->
    <el-dialog v-model="dialogVisible" title="发布助农商品" width="50%">
      <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="120px">
        <el-form-item label="选择商家" prop="merchantId">
          <el-button type="primary" @click="showMerchantDialog">选择商家</el-button>
          <div v-if="productForm.merchantId" style="margin-top: 10px;">
            已选择商家: {{ selectedMerchantName }} (ID: {{ productForm.merchantId }})
          </div>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="productForm.description" type="textarea" :rows="3" placeholder="请输入商品描述" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="productForm.price" :min="0" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="productForm.unit" placeholder="请输入单位(如: 斤、个、箱等)" />
        </el-form-item>
        <el-form-item label="产地" prop="origin">
          <el-input v-model="productForm.origin" placeholder="请输入商品产地" />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              :http-request="customImageUpload"
          >
            <div class="avatar-wrapper">
              <img
                  v-if="productForm.imageUrls"
                  :src="productForm.imageUrls"
                  class="avatar-image"
              />
              <div v-else class="avatar-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <span class="upload-text">上传商品图片</span>
              </div>
              <div class="upload-mask">
                <el-icon class="upload-icon"><Edit /></el-icon>
                <span class="upload-text">更换图片</span>
              </div>
            </div>
          </el-upload>
          <div class="upload-tip">建议上传清晰的产品图片，大小不超过5MB</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 商家选择弹窗 -->
    <el-dialog v-model="merchantDialogVisible" title="选择商家" width="70%">
      <div class="store-management-container">
        <div class="header">
          <div class="header-actions">
            <el-input
                v-model="merchantSearchQuery"
                placeholder="搜索店铺名称或地址"
                clearable
                @clear="handleMerchantSearchClear"
                @keyup.enter="handleMerchantSearch"
                style="width: 300px; margin-bottom: 15px;"
            >
              <template #append>
                <el-button :icon="Search" @click="handleMerchantSearch" />
              </template>
            </el-input>
          </div>
        </div>

        <el-table
            :data="merchantPaginatedData"
            stripe
            style="width: 100%"
            v-loading="merchantLoading"
            @row-click="handleMerchantRowClick"
            highlight-current-row
        >
          <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
          <el-table-column prop="shopName" label="店铺名称" width="180"></el-table-column>
          <el-table-column prop="address" label="店铺地址" show-overflow-tooltip></el-table-column>
          <el-table-column prop="contactPhone" label="联系电话" width="150" align="center"></el-table-column>
          <el-table-column label="店铺头像" width="120" align="center">
            <template #default="scope">
              <el-popover placement="right" :width="200" trigger="hover">
                <template #reference>
                  <el-avatar
                      :size="50"
                      :src="scope.row.shopAvatar || defaultAvatar"
                      shape="square"
                      fit="cover"
                  />
                </template>
                <div class="avatar-preview">
                  <img
                      :src="scope.row.shopAvatar || defaultAvatar"
                      alt="店铺头像"
                      class="preview-image"
                  />
                  <p class="avatar-text">店铺头像预览</p>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120" align="center">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ formatStatus(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
              v-model:current-page="merchantPagination.currentPage"
              v-model:page-size="merchantPagination.pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :small="false"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="merchantFilteredData.length"
              @size-change="handleMerchantSizeChange"
              @current-change="handleMerchantCurrentChange"
              :disabled="merchantLoading"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="merchantDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmMerchantSelection">确认选择</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from "axios"
import {Plus, Search, Edit} from '@element-plus/icons-vue'

// 从 localStorage 获取用户信息
const userStr = localStorage.getItem('admin')
const user = userStr ? JSON.parse(userStr) : null

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 商品表单数据
const productForm = reactive({
  merchantId: null,
  name: '',
  description: '',
  price: 0,
  stock: 0,
  unit: '',
  origin: '',
  imageUrls: ''
})

// 选中的商家名称
const selectedMerchantName = ref('')

// 表单验证规则
const rules = reactive({
  merchantId: [
    {required: true, message: '请选择商家', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入商品名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur'}
  ],
  price: [
    {required: true, message: '请输入价格', trigger: 'blur'}
  ],
  stock: [
    {required: true, message: '请输入库存', trigger: 'blur'}
  ],
  unit: [
    {required: true, message: '请输入单位', trigger: 'blur'}
  ],
  origin: [
    {required: true, message: '请输入产地', trigger: 'blur'}
  ]
})

// 图片列表
const imageList = ref([])
const productFormRef = ref(null)

// 弹窗显示状态
const dialogVisible = ref(false)
const merchantDialogVisible = ref(false)

// 商品列表数据
const productList = ref([])
const loading = ref(false)

// 查询表单
const searchForm = reactive({
  name: '',
  origin: '',
  status: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 商家相关数据
const merchantList = ref([])
const merchantLoading = ref(false)
const merchantSearchQuery = ref('')
const currentSelectedMerchant = ref(null)

// 商家分页配置
const merchantPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 计算属性：过滤后的商家数据
const merchantFilteredData = computed(() => {
  if (!merchantSearchQuery.value) return merchantList.value

  return merchantList.value.filter(item => {
    return (
        item.shopName.toLowerCase().includes(merchantSearchQuery.value.toLowerCase()) ||
        item.address.toLowerCase().includes(merchantSearchQuery.value.toLowerCase())
    )
  })
})

// 计算属性：分页后的商家数据
const merchantPaginatedData = computed(() => {
  const start = (merchantPagination.currentPage - 1) * merchantPagination.pageSize
  const end = start + merchantPagination.pageSize
  return merchantFilteredData.value.slice(start, end)
})

// 计算属性：过滤后的商品数据
const filteredData = computed(() => {
  return productList.value.filter(item => {
    const nameMatch = !searchForm.name || item.name.toLowerCase().includes(searchForm.name.toLowerCase())
    const originMatch = !searchForm.origin || item.origin.toLowerCase().includes(searchForm.origin.toLowerCase())
    const statusMatch = searchForm.status === null || item.status === searchForm.status
    return nameMatch && originMatch && statusMatch
  })
})

// 计算属性：分页后的商品数据
const paginatedData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredData.value.slice(start, end)
})

// 显示添加弹窗
const showAddDialog = () => {
  // 重置表单
  productFormRef.value?.resetFields()
  productForm.imageUrls = ''
  productForm.merchantId = null
  selectedMerchantName.value = ''
  dialogVisible.value = true
}

// 显示商家选择弹窗
const showMerchantDialog = () => {
  if (merchantList.value.length === 0) {
    fetchMerchantList()
  }
  merchantDialogVisible.value = true
}

// 获取商家列表
const fetchMerchantList = async () => {
  try {
    merchantLoading.value = true
    // 发送查看店铺请求
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selStore`, {
      withCredentials: true
    })

    if (response.data.code === 2000) {
      merchantList.value = response.data.data || []
      merchantPagination.total = merchantList.value.length
    } else {
      ElMessage.error(response.data.msg || '获取商家列表失败')
      merchantList.value = []
    }
  } catch (error) {
    console.error('获取商家列表失败:', error)
    ElMessage.error('获取商家列表失败，请稍后重试')
    merchantList.value = []
  } finally {
    merchantLoading.value = false
  }
}

// 处理商家行点击
const handleMerchantRowClick = (row) => {
  currentSelectedMerchant.value = row
  productForm.merchantId = row.id
  selectedMerchantName.value = row.shopName
}

// 确认商家选择
const confirmMerchantSelection = () => {
  if (!currentSelectedMerchant.value) {
    ElMessage.warning('请选择商家')
    return
  }
  merchantDialogVisible.value = false
}

// 处理商家搜索
const handleMerchantSearch = () => {
  merchantPagination.currentPage = 1
}

// 清空商家搜索
const handleMerchantSearchClear = () => {
  merchantSearchQuery.value = ''
  merchantPagination.currentPage = 1
}

// 处理商家分页大小变化
const handleMerchantSizeChange = (val) => {
  merchantPagination.pageSize = val
  merchantPagination.currentPage = 1
}

// 处理商家当前页变化
const handleMerchantCurrentChange = (val) => {
  merchantPagination.currentPage = val
}

// 格式化状态
const formatStatus = (status) => {
  return status === 1 ? '营业中' : status === 0 ? '待审核' : '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  return status === 1 ? 'success' : status === 0 ? 'warning' : 'info'
}

// 图片上传前校验
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }

  return isImage && isLt5M
}

// 自定义图片上传
const customImageUpload = async (options) => {
  const {file} = options
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', user?.id || '123')

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    })

    if (response.data.code === 2000) {
      ElMessage.success('图片上传成功')
      productForm.imageUrls = response.data.data
    } else {
      throw new Error(response.data.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传出错：' + error.message)
    throw error
  }
}

// 提交表单
const submitForm = async () => {
  try {
    // 验证表单
    await productFormRef.value.validate()

    // 如果没有上传图片，使用默认图片
    if (!productForm.imageUrls) {
      productForm.imageUrls = defaultAvatar
    }

    // 构建表单数据
    const formData = {
      ...productForm,
      imageUrls: productForm.imageUrls
    }

    // 显示加载状态
    const submitBtn = document.querySelector('.el-dialog__footer .el-button--primary')
    if (submitBtn) {
      submitBtn.disabled = true
    }

    // 调用API
    const response = await axios.post(`${BASE_URL}/api/v1/product/addAgricultureProduct`, formData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 2000) {
      ElMessage.success('助农商品发布成功')
      dialogVisible.value = false
      // 刷新列表
      fetchProductList()
    } else {
      ElMessage.error(response.data.message || '发布失败')
    }
  } catch (error) {
    console.error('提交表单错误:', error)
    if (error.name !== 'ValidationError') {
      ElMessage.error('发布失败: ' + (error.response?.data?.message || error.message))
    }
  } finally {
    if (document.querySelector('.el-dialog__footer .el-button--primary')) {
      document.querySelector('.el-dialog__footer .el-button--primary').disabled = false
    }
  }
}

// 获取商品列表
const fetchProductList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      pageNum: 1, // 前端分页不需要传页码给后端
      pageSize: 1000 // 获取所有数据，前端进行分页
    }

    const response = await axios.get(`${BASE_URL}/api/v1/government/public/list`, {params})
    if (response.data.code === 2000) {
      productList.value = response.data.data || []
      // 更新分页总数
      pagination.total = filteredData.value.length
    } else {
      ElMessage.error(response.data.message || '获取商品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 查询商品
const handleSearch = () => {
  pagination.currentPage = 1
  pagination.total = filteredData.value.length
}

// 重置查询
const resetSearch = () => {
  searchForm.name = ''
  searchForm.origin = ''
  searchForm.status = null
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
}

// 删除商品
const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该商品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.post(`${BASE_URL}/api/v1/product/delAgricultureProduct/${id}`)
      if (response.data.code === 2000) {
        ElMessage.success('删除成功')
        // 如果当前页最后一条数据被删除，且不是第一页，则返回上一页
        if (filteredData.value.length === 1 && pagination.currentPage > 1) {
          pagination.currentPage -= 1
        }
        fetchProductList()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 初始化加载数据
onMounted(() => {
  fetchProductList()
})
</script>

<style scoped>
.agriculture-product-container {
  padding: 20px;
}

.search-container {
  margin: 20px 0;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 图片上传样式 */
.avatar-uploader {
  --el-avatar-size: 178px;
}

.avatar-wrapper {
  position: relative;
  width: var(--el-avatar-size);
  height: var(--el-avatar-size);
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}

/* 商家选择弹窗样式 */
.store-management-container {
  padding: 0;
  background-color: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.store-table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.avatar-preview {
  text-align: center;
  padding: 10px;
}

.preview-image {
  width: 100%;
  height: auto;
  max-height: 200px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.avatar-text {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

.el-table {
  font-size: 14px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>